var express = require('express');
var router = express.Router();
const { connect,mongoose } = require('../../db/mongodb');
const UserModel = require('../../models/UserModel');
const md5 = require('md5');
const jwt = require('jsonwebtoken');
// 注册页
router.get('/register', function (req, res, next) {
    res.render('register', { title: '用户注册', currentPage: 'register' });
});
// 注册接口
router.post('/api/register', function (req, res, next) {
    const { username, password,confirmPassword } = req.body;
    if (password !== confirmPassword) {
        res.json({ "code": "2001", "msg": "两次密码不一致", "data": null });
        return;
    }
    console.log(username, password,confirmPassword);
    UserModel.create({
        username,
        password: md5(password)
    }).then((data) => {
        res.json({ "code": "0000", "msg": "注册成功", "data": null });
    }).catch((err) => {
        res.json({ "code": "1002", "msg": `注册失败: ${err.message}`, "data": null });
    })
});

// 登录页
router.get('/login', function (req, res, next) {

    res.render('login', { title: '用户登录', currentPage: 'login' });
});
// 登录接口
router.post('/api/login', function (req, res, next) {
    const { username, password } = req.body;
    console.log(username, password );
    // 查询用户时应该只按用户名查询，然后在代码中比较密码
    UserModel.findOne({
        username
    }).then((data) => {
        console.log(data);
        if (data) {
            console.log(data);
            if (data.password !== md5(password)) {
                res.json({ "code": "2001", "msg": "用户名或密码错误", "data": null });
                return;
            }
            // 登录成功，将用户信息存入session中
            req.session.username = data.username;
            req.session._id = data._id;
            // 登录时刷新session有效期
            req.session.cookie.maxAge = 1000 * 60 * 60 * 24 * 7;
            let token = jwt.sign({
                username: data.username,
                _id: data._id
            }, 'account', { expiresIn: '1h' })
            req.cookies.token = token;
            res.json({ "code": "0000", "msg": "登录成功", "data": token });
        }else{  
            res.json({ "code": "2002", "msg": "用户名不存在", "data": null });
        }
    }).catch((err) => {
        res.json({ "code": "1001", "msg": "登录失败", "data": null });
    })
});

router.get('/logout', function (req, res, next) {
    req.session.destroy(err => {
        if(err){
            return res.json({ "code": "3001", "msg": "退出失败", "data": null });
        }
        res.clearCookie('sid');
        res.redirect('/login');
    });
});


module.exports = router;
